// pages/floor/template/tpl9001/tpl9001.js
import * as API_Shop from '../../../api/shop.js'
import * as API_Trade from '../../../api/trade.js'
import { Foundation } from '../../../ui-utils/index.js'
const app = getApp();
let util = require('../../../utils/util.js')

Component({
  options: {
    addGlobalClass: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    catsTypeList: {
      type: Array,
      value: []
    },
    cartList: {
      type: Array,
      value: []
    },
    heightData: {
      type: Object,
      value: {}
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    fixedTop: {},
    minHeight: 0,
    needHeight: false,
    // 1级分组
    activeType: 0,
    typeData: [],
    // 团购商品
    goodsData: [],
    // 商品分页
    page_no: 1,
    page_size: 10,
    page_count: 0,
    playId: ''
  },
  // 生命周期
  lifetimes: {
    async ready() {
      this.setData({
        minHeight: app.globalData.systemInfo.screenHeight
      });
    }
  },
  // 数据监听器
  observers: {
    catsTypeList(newVal) {
      this.setData({
        activeType: 0,
        typeData: newVal,
        goodsData: [],
        page_no: 1
      });
      this.getShetuanGoods();
    },
    cartList(newVal) {
      this.cartContrast();
    },
    heightData(newVal) {
      this.setData({
        fixedTop: newVal,
        needHeight: !!newVal && !!newVal.scrollY
      });
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 1级切换分组
    async selectType(e) {
      let _index = e.currentTarget.dataset.index;
      const { activeType } = this.data;
      if (activeType !== _index) {
        await this.setData({
          goodsData: [],
          activeType: _index,
          page_no: 1
        });
        this.getShetuanGoods();
      };
    },
    // 获取商品列表
    getShetuanGoods() {
      let { activeType, typeData, page_no, page_size } = this.data;
      // 位置信息
      let { latitude, longitude } = app.globalData.locationData;
      let _params = {
        page_no,
        page_size,
        shop_cat_id: typeData[activeType].shop_cat_id,
        user_lat: latitude,
        user_lng: longitude
      };
      API_Shop.getShetuanGoods(_params).then(res => {
        const { data, data_total, page_size } = res;
        let _pageCount = Math.ceil(data_total / page_size);
        let _list = data || [];
        _list.forEach(item => {
          item.shetuan_price = Foundation.formatPrice(item.shetuan_price);
          item.priceInt = item.shetuan_price ? item.shetuan_price.split('.')[0] : '0';
          item.pricePoint = item.shetuan_price ? item.shetuan_price.split('.')[1] : '00';
        });
        _list = this.data.goodsData.concat(data);
        this.setData({
          needHeight: _list.length > 1
        });
        this.setData({
          goodsData: _list,
          page_count: _pageCount
        });
        const { fixedTop } = this.data;
        if (fixedTop && fixedTop.scrollY && activeType && page_no === 1) {
          this.showGroupTpl();
        };
      });
    },
    // 滚动到团购商品组件
    showGroupTpl: function() {
      const navHeight = app.globalData.navbar.height;
      var query = wx.createSelectorQuery();
      query.selectViewport().scrollOffset();
      query.select('#tpl9001').boundingClientRect();
      query.exec(res => {
        var miss = res[0].scrollTop + res[1].top - navHeight + 1;
        wx.pageScrollTo({
          scrollTop: miss,
          duration: 0
        });
      });
    },
    // 图片跳转商品详情页面
    getHref(e) {
      const { video, id, sku } = e.currentTarget.dataset;
      if (video) {
        return;
      };
      wx.navigateTo({
        url: `/pages/goods/goods?goods_id=${id}&sku_id=${sku}`
      });
    },
    // 视屏显示
    playVideo: function (e) {
      const { id, index } = e.currentTarget.dataset;
      let { goodsData, playId } = this.data;
      goodsData[index].showVideo = true;
      // 暂停当前播放的视频
      if (playId) {
        let currentVideo = wx.createVideoContext(playId, this);
        currentVideo.pause();
      };
      let videoplay = wx.createVideoContext(id, this);
      videoplay.play();
      this.setData({
        goodsData,
        playId: id
      });
    },
    // 视屏继续播放
    playContinue: function (e) {
      const { id } = e.currentTarget.dataset;
      let { playId } = this.data;
      // 暂停当前播放的视频
      if (id !== playId) {
        let currentVideo = wx.createVideoContext(playId, this);
        currentVideo.pause();
        this.setData({
          playId: id
        });
      };
    },
    // 首次加入购物车
    async addCart(e) {
      wx.vibrateShort({});
      let _isLogin = await app.isLogin();
      if (!_isLogin) { return };
      const _index = e.currentTarget.dataset.index;
      let { goodsData } = this.data;
      const _sku_id = goodsData[_index].sku_id;
      const _active_id = goodsData[_index].shetuan_id;
      const _buyNum = 1; // 数量
      API_Trade.addToCart(_sku_id, _buyNum, _active_id).then(response => {
        goodsData[_index].cart_num = 1;
        this.setData({
          goodsData
        });
      });
    },
    /** 更新商品数量 */
    async handleUpdateSkuNum(e) {
      const that = this;
      const _index = e.currentTarget.dataset.index;
      const { goodsData } = this.data;
      const { sku_id, cart_num, enable_quantity } = goodsData[_index];
      const symbol = e.currentTarget.dataset.symbol;
      if (!symbol || typeof symbol !== 'string') {
        if (!e.detail.value) return
        let _num = parseInt(e.detail.value)
        if (isNaN(_num) || _num < 1) {
          wx.showToast({ title: '输入格式有误，请输入正整数', icon: 'none' })
          return
        }
        if (_num >= enable_quantity) {
          wx.showToast({ title: '超过最大库存', icon: 'none' })
          return
        }
        this.updateSkuNum({ sku_id: sku_id, num: _num })
      } else {
        wx.vibrateShort({});
        if (symbol === '-' && cart_num < 2) {
          wx.showModal({
            title: '提示',
            content: '确定要删除此商品吗?',
            confirmColor: '#f42424',
            success(res) {
              /** 删除 */
              if (res.confirm) {
                API_Trade.deleteSkuItem(sku_id, 'SHETUAN_CART').then(_ => {
                  goodsData[_index].cart_num = 0;
                  that.setData({
                    goodsData
                  });
                }).catch()
              }
            }
          });
          return;
        };
        if (symbol === '+' && cart_num >= enable_quantity) {
          wx.showToast({ title: '超过最大库存', icon: 'none' })
          return
        };
        let _num = symbol === '+' ? cart_num + 1 : cart_num - 1
        this.updateSkuNum({ sku_id: sku_id, num: _num, index: _index })
      };
    },
    /* 更新sku数据 */
    updateSkuNum(params) {
      setTimeout(() => {
        API_Trade.updateSkuNum(params.sku_id, params.num, 'SHETUAN_CART').then(_ => {
          const { goodsData } = this.data;
          goodsData[params.index].cart_num = params.num;
          this.setData({
            goodsData
          });
        }).catch()
      }, 200)
    },
    /** 上拉触底加载事件 */
    getNextList: function() {
      let { page_no, page_count } = this.data;
      this.setData({ 
        page_no: page_no += 1
      });
      if (page_count >= page_no) {
        this.getShetuanGoods();
      } else {
        let { activeType, typeData } = this.data;
        if (typeData && activeType < typeData.length - 1) {
          this.setData({
            goodsData: [],
            page_no: 1,
            activeType: activeType += 1
          });
          this.getShetuanGoods();
        };
      };
    },
    /* 对比购物车更新商品的数量 */
    cartContrast: async function() {
      let { goodsData } = this.data;
      if (goodsData && goodsData.length) {
        let _newUseData = await app.cartContrast(goodsData);
        this.setData({
          goodsData: _newUseData
        });
      };
    }
  }
})
